Home | | Latest | About | Random
# Week 6 Monday
Dear Class,
Your exam is being graded, hopefully by the end of today (Monday). When they are available they will be viewable on Gradescope, I'll send a message. Please look them over when they are released. Make sure to figure out how to do the problems that you missed, and even if you got them right, please review them as well.
Just a heads up that midterm 2 is Week 8 Monday, so that is coming soon in 2 weeks time! Use this opportunity to strategize how you might study or prepare differently. It will cover up to and including section 14, as well as HW4 (on Gradescope). Certainly, you want to know all your previous material as well, as the material builds on itself! The new stuff:
- Section 9 Functions
- Section 10 References
- Section 11 Vector class template
- Section 12 Choosing parameter types
- Section 13 Header files and multiple files
- Section 14 Function overloading
As we will need to be able to handle **multiple files** properly soon for our class by using your IDE (whether XCode or VS Code Community), there are some videos posted in the **media gallery** on BruinLearn showing you how to do that (named "**multiple_files**" and "**hpp_cpp**").
-- B
## The story from last time... A `print` function for `vector`. Pass by value or pass by argument?
Last time we wrote a function `print` to print out a `vector` (a vector of ints), as `cout <<` doesn't have a built in way to do it (yet, til PIC10B).
**We first** wrote our `print` function to be something like this
```cpp
/**
Prints the elements of a vector of ints, like { 3, 1, 4 }.
@param v : the vector to print
*/
void print(vector v) {
if (v.empty()) {
cout << "{ }" << endl;
return;
}
cout << "{ ";
for (size_t i = 0; i < v.size() - 1; ++i) {
cout << v[i] << ", ";
}
cout << v[v.size() - 1] << " }" << endl;
}
```
If we have the following in `main`
```cpp
vector data = {1, 2, 3, 4, 5};
print(data);
```
Then it would indeed print out
```
{ 1, 2, 3, 4, 5 }
```
Here we pass an argument **by value** in to `print`, which is _not so great_ a design since that would make a copy of the value that we then assign to the parameter `v` here. This is especially not great when the argument vector we pass in has millions of entries.
So the **next thing** we do is, since this `data` variable exists already, why not just reference it instead, so let us rewrite our `print` function so we pass in the argument by reference instead? So we go from `void print(vector v)` to `void print(vector& v)` instead.
.
.
.
.
.
To maybe see an appreciative difference, let us quickly write a function call `average` that finds the average of a `vector` of `double`s, and experiment with pass by value or pass by reference for the argument.
```cpp
double average(vector data) {
double sum = 0;
for(size_t i = 0 ; i < data.size(); ++i) {
sum += data.at(i);
}
return sum / data.size();
}
```
Try with both
```cpp
double average(vector data) // pass by value
```
and
```cpp
double average(vector& data) // pass by reference
```
on the input data
```cpp
vector data(100000000, 3.14); // 100 million entries
cout << average(data);
```
Do you see a difference in execution time?
.
.
.
.
.
## `const` correctness.
Ok so far that is great, but now you are thinking. The data we pass in in above example to `print` or to find its `average`, we never needed to modify the data. So it is entirely possible that the argument variables themselves are `const`, a "read-only" variable, like this
```cpp
const vector data = {1, 2, 3, 4, 5}; // a read-only variable
```
But then when we pass it into our `average` function by reference, namely
```cpp
double average(vector data)
```
we get a build error!
```cpp
average(data) // build error!
```
If we change it to pass by value, namely
```cpp
double average(vector data)
```
then it works. But this requires us to make a copy of this variable, which we want to avoid!
So magically, a solution is to **pass by reference to `const`**, namely have the parameter to be a reference to const, like this
```cpp
double average(const vector& data)
```
And this version with the parameter `const vector& data` being a **reference to `const`**, we can also pass in an argument that is not const!
The main idea being:
- A non-`const` reference cannot reference to `const`s!
- A reference to `const` can reference to both `const`s and non-`const`s!
Using the right `const` variable or references is generally called **`const` correctness**, and it is important at build time for the compiler to help you whether you made an unintended error or not. Let us speak more of this reference to `const`.
.
.
.
.
.
## Reference to `const`.
```cpp
int i = 1; // An initialized int variable i, holding value 1
const int& r = i; // A reference to const
```
The type of `r` is `const int&`, read aloud "const int ref", a **reference to `const`**. It is still an arrow to `i`, but a **read-only** arrow: we can read `i` through `r`, but *not change* `i` through `r`.
```cpp
#include
using namespace std;
int main() {
int i = 1;
const int& r = i;
cout << i << ' ' << r << endl;
i = 5; // fine, i itself is not const
cout << i << ' ' << r << endl;
// r = 7; // BUILD ERROR: cannot change i through a read-only arrow
return 0;
}
```
Output:
```
1 1
5 5
```
`r` still **sees** every change to `i`, it just cannot **make** any.
.
.
.
.
.
### Which arrows are allowed?
Which lines give a build error? Comment them out, then what is the output?
```cpp
#include
using namespace std;
int main() {
int i = 1;
const int j = 2;
i = 11;
j = 22;
int& r = i;
const int& s = i;
r = 111;
s = -111;
int& t = j;
const int& u = j;
u = -1111;
int& p = r;
const int& q = r;
p = 11111;
q = -11111;
int& x = s;
const int& y = s;
y = -111111;
cout << i << ' ' << j;
return 0;
}
```
.
.
.
.
.
Answer and comments.
```cpp
#include
using namespace std;
int main() {
int i = 1;
const int j = 2;
i = 11;
// j = 22; // BUILD ERROR: j is const
int& r = i;
const int& s = i;
r = 111; // i is now 111
// s = -111; // BUILD ERROR: s is a read-only arrow
// int& t = j; // BUILD ERROR: would remove const from j
const int& u = j;
// u = -1111; // BUILD ERROR: u is a read-only arrow
int& p = r; // p is an arrow to i
const int& q = r; // q is a read-only arrow to i
p = 11111; // i is now 11111
// q = -11111; // BUILD ERROR: q is a read-only arrow
// int& x = s; // BUILD ERROR: would remove const from s
const int& y = s; // y is a read-only arrow to i
// y = -111111; // BUILD ERROR: y is a read-only arrow
cout << i << ' ' << j;
return 0;
}
```
Output:
```
11111 2
```
| | to `int i` | to `const int j` | to `int& r` | to `const int& s` |
| -------------- | ---------- | ---------------- | ----------- | ----------------- |
| `int& t` | ok | **build error** | ok | **build error** |
| `const int& u` | ok | ok | ok | ok |
Why is `int& t = j;` a build error? If it were allowed, `t = 1111;` would change `j`, a `const`, through the back door `t`! C++ protects us from ourselves.
**Rule of thumb.** You can always **gain** `const` (a read-only arrow to something changeable is fine), but you can never **remove** it.
**Remark. Arrows never point to arrows.** `p`, `q`, `y` all point straight at `i`, not at `r` or `s`. And `int& x = s;` is a build error even though `i` is changeable: the compiler only sees that `s` is read-only. **Once you are behind a read-only arrow, everything after it stays read-only.** (Try review question 3 in 10.6!)
Think of sharing a document: if a friend gives you **view-only** access, you cannot give someone else **edit** access to it!
//// We will continue this next time.
## For functions, how do we pick the parameter type?
There are three options for a pass an argument (of type `T`) into a parameter of a function
- `T`: by value
- `T&`: by reference
- `const T&`: by reference to `const`
We can ask:
| Do you want to mutate the argument? | Do you want to avoid copying it? | Use |
|---|---|---|
| Yes | Either | `T&` |
| No | Yes | `const T&` |
| No | No | `T` (simplest) |
And to answer "Do you want to avoid copying it", often boils down to the type of data being passed in is a class type or not:
- **Fundamental types:** These take about 1 to 8 bytes and are cheap to copy, so pass them by value is often fine.
- **Class types:** These can be huge, like a `std::string` holding all of Shakespeare or a large `std::vector`, so they're usually passed by `const T&`.
- This is **rule of thumb** that works "in many situations, but not all."
### Const correctness matters when you work with others
- If a function doesn't change its argument, mark the parameter `const`. This avoids a copy and also tells the reader it won't be changed.
- Skipping `const` can break someone else's code.
- Say you have a function `sum` that takes a `vector&`,
- And you have another function `print_sum(const vector& w)` in which in the body calls `sum`. Then it won't build, even if `print_sum` is written correctly.
That is if we have:
```cpp
int sum(vector& data) {
int sum = 0;
for (size_t i = 0 ; i < data.size(); i++){
sum += data.at(i);
}
return sum;
}
void print_sum(const vector& data) {
cout << sum(data);
}
```
Then
```cpp
vector data = {1, 2, 3};
print_sum(data); // build error!
```
(There are two ways to make `print_sum` above to actually print out the sum, but one is much preferable. Can you determine which is which?)
## Try it!
Review the list of member functions the `vector` class has. One thing from `string` that is missing from `vector` is concatenation. So what if we want to join two `vector`s say `a` and `b` into one single `vector`?
Approach 1. Say we write a function call `join` that return a **new** `vector` that we pass in two `vector` arguments.
- What would be a good choice for its function signature? Namely, should we pass by value or by reference?
- Try writing it! Along with function comments.
Approach 2. Say we write a function call `cat` that takes in two `vector`s `a` and `b` by **modifying** `a` by concatenating entries of `b`.
- What would be a good choice for its function signature?
- Try writing it! Along with function comments.
- Note, there is a sneaky bug you may run in when you do `cat(a, a)` (concatenating itself to itself) that could give you an infinite loop. See if you can fix it!!
[[1-teaching/ucla-2026-fall-pic-10a/join-and-concatenate-answers|join-and-concatenate-answers]]